package com.fsnbigdata.web;
import com.fsnbigdata.domain.Organism;
import com.fsnbigdata.domain.Park;
import com.fsnbigdata.enums.ResultEnum;
import com.fsnbigdata.exception.ParamException;
import com.fsnbigdata.util.ReflectUtil;
import io.swagger.annotations.*;
import org.springframework.roo.addon.web.mvc.controller.annotations.ControllerType;
import org.springframework.roo.addon.web.mvc.controller.annotations.RooController;
import org.springframework.roo.addon.web.mvc.controller.annotations.responses.json.RooJSON;
import com.fsnbigdata.service.api.ParkService;
import io.springlets.web.NotFoundException;
import javax.validation.Valid;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.servlet.mvc.method.annotation.MvcUriComponentsBuilder;
import org.springframework.web.util.UriComponents;
import springfox.documentation.annotations.ApiIgnore;

import java.lang.reflect.Method;

/**
 * = ParksItemJsonController
 *
 * TODO Auto-generated class documentation
 *
 */
@RooController(entity = Park.class, pathPrefix = "/api", type = ControllerType.ITEM)
@RooJSON
@RestController
@RequestMapping(value = "/api/parks/{id}", name = "ParksItemJsonController", produces = MediaType.APPLICATION_JSON_VALUE)
@Api(tags = "Park", description = "动植物园" )
public class ParksItemJsonController {

    /**
     * TODO Auto-generated attribute documentation
     *
     */
    private ParkService parkService;

    /**
     * TODO Auto-generated constructor documentation
     *
     * @param parkService
     */
    @Autowired
    public ParksItemJsonController(ParkService parkService) {
        this.parkService = parkService;
    }

    /**
     * TODO Auto-generated method documentation
     *
     * @return ParkService
     */
    public ParkService getParkService() {
        return parkService;
    }

    /**
     * TODO Auto-generated method documentation
     *
     * @param parkService
     */
    public void setParkService(ParkService parkService) {
        this.parkService = parkService;
    }

    /**
     * TODO Auto-generated method documentation
     *
     * @param id
     * @return Park
     */
    @ModelAttribute
    public Park getPark(@PathVariable("id") Long id) {
        Park park = parkService.findOne(id);
        if (park == null) {
            throw new NotFoundException(String.format("Park with identifier '%s' not found", id));
        }
        return park;
    }

    /**
     * TODO Auto-generated method documentation
     *
     * @param park
     * @return ResponseEntity
     */
    @GetMapping(name = "show")
    @ApiResponses({
            @ApiResponse(code = 200, message = "", response = Park.class)
    })
    @ApiImplicitParams({
            @ApiImplicitParam(name = "id", value = "", paramType = "path", dataType = "int", required = true)
    })
    //@PreAuthorize("hasRole('USER')")
    public ResponseEntity<?> show(@ApiIgnore @ModelAttribute Park park) {
        return ResponseEntity.ok(park);
    }

    /**
     * TODO Auto-generated method documentation
     *
     * @param park
     * @return UriComponents
     */
    public static UriComponents showURI(Park park) {
        return MvcUriComponentsBuilder.fromMethodCall(MvcUriComponentsBuilder.on(ParksItemJsonController.class).show(park)).buildAndExpand(park.getId()).encode();
    }

    /**
     * TODO Auto-generated method documentation
     *
     * @param storedPark
     * @param park
     * @param result
     * @return ResponseEntity
     */
    @PutMapping(name = "update")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "id", value = "", paramType = "path", dataType = "int", required = true)
    })
    @PreAuthorize("hasRole('DB_PARK')")
    @ApiOperation(value = "",notes = "update")
    public ResponseEntity<?> update(@ApiIgnore @ModelAttribute Park storedPark, @Valid @RequestBody Park park, BindingResult result) throws Exception {
        if (result.hasErrors()) {
            throw new ParamException(ResultEnum.PARAM_ERROR.getCode(),
                    result.getFieldError().getDefaultMessage());
        }
        park.setId(storedPark.getId());
        park.getDistricts().forEach(district -> {
            district.setPark(park);
            district.getOrganisms().forEach(organism -> {
                organism.setParkDistrict(district);
                organism.getImages().forEach(image -> image.setParkDistrictOrganism(organism));
            });
        });
        String name = getParkService().findOne(storedPark.getId()).getName();
        Park newPark = getParkService().save(park);
        Class<?> clazz = ParksItemJsonController.class;
        Method method = clazz.getMethod("update", ReflectUtil.getPeremeterClass(clazz, "update"));
        ReflectUtil.setAnnotationOn(method,"更新数字化动物园，名称："+name);
        return ResponseEntity.ok(newPark);
    }

    /**
     * TODO Auto-generated method documentation
     *
     * @param park
     * @return ResponseEntity
     */
    @DeleteMapping(name = "delete")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "id", value = "", paramType = "path", dataType = "int", required = true)
    })
    @PreAuthorize("hasRole('DB_PARK')")
    @ApiOperation(value = "",notes = "delete")
    public ResponseEntity<?> delete(@ApiIgnore @ModelAttribute Park park) throws Exception {
        getParkService().delete(park);
        Class<?> clazz = ParksItemJsonController.class;
        Method method = clazz.getMethod("delete", ReflectUtil.getPeremeterClass(clazz, "delete"));
        ReflectUtil.setAnnotationOn(method,"删除数字化动物园，名称："+park.getName());
        return ResponseEntity.ok().build();
    }
}
